<?php
namespace App\Http\Controllers\Admin;

use App\Utils\DataBackupUtil;

class DatabackupController extends BaseController
{

    public function __construct()
    {
        parent::__construct();
        $config = [
            'compress' => 1,  //数据库备份文件是否启用压缩 0不压缩 1 压缩
            'level' => 5,
        ];
        $this->DB = new DataBackupUtil($config);
    }


    /**
     * 显示资源列表
     * @return \think\Response
     */
    public function index()
    {
        $db = $this->DB;
        $list = $db->fileList();
        if(request()->ajax()){
            if($list) {
                $data = [];
                foreach ($list as $k => $v) {
                    $data[$k]['filename'] = $v['filename'];
                    $data[$k]['part'] = $v['part'];
                    $data[$k]['size'] = $v['size'] . 'B';
                    $data[$k]['compress'] = $v['compress'];
                    $data[$k]['backtime'] = $k;
                    $data[$k]['time'] = $v['time'];
                }
                krsort($data);//根据时间降序
            }
            return json_encode(['code'=>0, 'msg'=>'OK', 'count'=>count($list), 'data'=>$data]);
        }
        return view('admin/sys/databackup/index',['total'=>count($list)]);
    }

    /**
     * 删除备份记录表
     */
    public function delFile()
    {
        try {
            $filename = request()->input("filename");
            $files = $this->DB->delFile($filename);
            return $this->result($files, 200, "删除成功");
        } catch (\Exception $e) {
            return $this->result("", 500, $e->getMessage());
        }
    }

    /**
     * 导入备份记录表
     */
    public function import()
    {
        $part = request()->post('part') != '' ? intval(request()->post('part')) : null;
        $start = request()->post('start') != '' ? intval(request()->post('start')) : null;
        $time = request()->post('time');
        $db = $this->DB;
        if (is_numeric($time) && is_null($part) && is_null($start)) {
            $list = $db->getFile('timeverif', $time);
            if (is_array($list)) {
                session(['backup_list'=>$list]);
                return $this->result(['part'=>1, 'start'=>0], 200, "初始化完成，请勿关闭或刷新本页面");
            } else {
                return $this->result("", 500, "备份文件可能已经损坏，请检查");
            }
        } else if (is_numeric($part) && is_numeric($start)) {
            $list = session("backup_list");
            $start = $db->setFile($list)->import($start);
            if (false === $start) {
                return $this->result("", 500, "还原数据出错");
            } elseif (0 === $start) {
                if (isset($list[++$part])) {
                    $data = array('part' => $part, 'start' => 0);
                    return $this->result($data, 200, "请稍等，正在还原...#{$part}");
                } else {
                    request()->session()->forget('backup_list');
                    return $this->result("", 0, "还原完成");
                }
            } else {
                $data = array('part' => $part, 'start' => $start[0]);
                if ($start[1]) {
                    $rate = floor(100 * ($start[0] / $start[1]));
                    return $this->result($data, 200, "请稍等，正在还原...#{$part}({$rate}%)");
                } else {
                    $data['gz'] = 1;
                    return $this->result($data, 200, "请稍等，正在还原...#{$part}");
                }
                return $this->result("", 200, "请稍等，正在还原...#{$part}");
            }
        } else {
            return $this->result("", 500, "参数错误");
        }
    }

    /**
     * 下载备份记录表
     */
    public function downloadFile()
    {
        $this->DB->downloadFile(request()->input("time"));
    }

    /**
     * 数据库的列表.
     * @return \think\Response
     */
    public function create()
    {
        $db = $this->DB;
        $list = $db->dataList();
        if(request()->ajax()){
            return json_encode(['code'=>0, 'msg'=>'OK', 'count'=>count($list), 'data'=>$list]);
        }
        return view('admin/sys/databackup/list',['total'=>count($list)]);
    }

    /**
     * 数据库操作
     * @param  int  $id
     * @return \think\Response
     */
    public function read()
    {
        $tables = explode(",", substr(request()->input("tables"), 1));
        $type = request()->input("type", "repair");
        if(empty($tables) || count($tables) == 0) {
            return $this->result("", 500, "系统繁忙，请重试");
        }
        switch ($type) {
            case 'backup': //备份
                return $this->backup($tables);
                break;
            case 'optimize': //优化
                return $this->optimize($tables);
                break;
            default: //修复
                return $this->repair($tables);
                break;
        }
    }

    /**
     * 备份表
     */
    public function backup($tables = [])
    {
        $db = $this->DB;
        $data = '';
        foreach ($tables as $k => $v) {
            $res = $db->backup($v, 0);
            if ($res == false && $res != 0) {
                $data .= $v . '|';
            }
        }
        $code = $data ? 500 : 200;
        $msg = $data ? '备份失败' . $data : '备份成功';
        return $this->result($tables, $code, $msg);
    }

    /**
     * 优化表
     */
    public function optimize($tables = [])
    {
        $db = $this->DB;
        try{
            $db->optimize($tables);
            return $this->result("", 0, "优化成功");
        }catch (\Exception $e){
            return $this->result($tables, 500, $e->getMessage());
        }
    }

    /**
     * 修复表
     */
    public function repair($tables = [])
    {
        $db = $this->DB;
        try{
            $db->repair($tables);
            return $this->result("", 0, "修复成功");
        }catch (\Exception $e){
            return $this->result($tables, 500, $e->getMessage());
        }
    }
}
